package com.centaline.androidsalesblog.fragments.entrust;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.activities.sale.RentDetailActivity;
import com.centaline.androidsalesblog.activities.sale.RentListActivity;
import com.centaline.androidsalesblog.activities.sale.SaleDetailActivity;
import com.centaline.androidsalesblog.activities.sale.SaleListActivity;
import com.centaline.androidsalesblog.adapter.ReservationAdapter;
import com.centaline.androidsalesblog.api.sale.StaffApi;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.ReserveUpdate;
import com.centaline.androidsalesblog.iml.ReserveItemCallback;
import com.centaline.androidsalesblog.model.businissobject.ReservationBo;
import com.centaline.androidsalesblog.model.businissobject.ReserveStaffNoBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.PostDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.responseobject.StaffRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 已约看
 * Created by ruanzb on 2016/5/9.
 */
public class ReservationFragment extends BaseReservationFragment {

    private RelativeLayout rl_list;
    private LinearLayout ll_no_list;
    private Button btn_sale, btn_rent;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private RecyclerViewExpandableItemManager expMgr;

    private StaffApi staffApi;
    private ArrayList<ReserveStaffNoBo> reserveStaffNoBoList = new ArrayList<>();
    private ArrayList<PostDo> postDoArrayList = new ArrayList<>();
    private ArrayList<String> staffNos = new ArrayList<>();
    private ReservationAdapter reservationAdapter;
    private int pageIndex;

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_reservation;
    }

    @Override
    protected void findViews(View view) {
        rl_list = (RelativeLayout) view.findViewById(R.id.rl_list);
        ll_no_list = (LinearLayout) view.findViewById(R.id.ll_no_list);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        btn_sale = (Button) view.findViewById(R.id.btn_sale);
        btn_rent = (Button) view.findViewById(R.id.btn_rent);
    }

    @Override
    protected void initView() {
        super.initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setHasOptionsMenu(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestReservationList();
            }
        });

        expMgr = new RecyclerViewExpandableItemManager(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(false);

        reservationAdapter = new ReservationAdapter(getContext(), GlideLoad.initRound(this), GlideLoad.init(this),
                reserveStaffNoBoList, new ReserveItemCallback() {

            @Override
            public void staffCallback(StaffDo staffDo, int tag) {

                startActivity(new Intent(getActivity(), ChatActivity.class)
                        .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo())));
            }

            @Override
            public void postItemCallbak(PostDo postDo) {

                if ("s".equalsIgnoreCase(postDo.getPostType())) {
                    //二手房
                    startActivity(new Intent(getActivity(), SaleDetailActivity.class)
                            .putExtra(ExtraConstant.PostId, postDo.getPostId()));
                } else {
                    //租房
                    startActivity(new Intent(getActivity(), RentDetailActivity.class)
                            .putExtra(ExtraConstant.PostId, postDo.getPostId()));
                }
            }
        });

        recyclerView.setAdapter(expMgr.createWrappedAdapter(reservationAdapter));
        expMgr.attachRecyclerView(recyclerView);

        staffApi = new StaffApi(ReservationFragment.class, StaffRo.class,
                new IResponseListener<StaffRo>() {
                    @Override
                    public void onResponse(StaffRo staffRo) {
                        StaffDo staffDo = staffRo.getStaffDo();
                        int size = reserveStaffNoBoList.size();
                        for (int i = 0; i < size; i++) {
                            if (reserveStaffNoBoList.get(i).getStaffNo().
                                    equalsIgnoreCase(staffDo.getStaffNo())) {
                                reserveStaffNoBoList.get(i).setStaffDo(staffDo);
                                expMgr.notifyGroupItemChanged(i);
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        reservationListApi.setCount(100);

        RxView.clicks(btn_sale)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(new Intent(getActivity(), SaleListActivity.class));
                    }
                });

        RxView.clicks(btn_rent)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(new Intent(getActivity(), RentListActivity.class));
                    }
                });

        bizUnit();
    }

    @Override
    protected void requestReservationList() {
        pageIndex = 0;
        postDoArrayList.clear();
        int count = reserveStaffNoBoList.size();
        if (count > 0) {
            reserveStaffNoBoList.clear();
            expMgr.notifyGroupItemRangeRemoved(0, count);
        }
        super.requestReservationList();
    }

    @Override
    protected void loadData() {
        if (!isRequest) {
            isRequest = true;
            swipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(true);
                    requestReservationList();
                }
            });
        }
    }

    @Subscribe
    public void onEventMainThread(ReserveUpdate reserveUpdate) {
        if (reserveUpdate.getStatus() == 1 ||
                reserveUpdate.getStatus() == -1) {
            if(isRequest){
                swipeRefreshLayout.setRefreshing(true);
                requestReservationList();
            }
        }
    }

    @Override
    protected boolean isReserve() {
        return true;
    }

    @Override
    protected void response(ArrayList<ReservationBo> temp) {
        reservationBoArrayList.addAll(temp);
        reserveStaffNoBoList.clear();
        staffNos.clear();

        ArrayList<Long> updateTimes = new ArrayList<>();
        for (ReservationBo reservationBo : reservationBoArrayList) {
            postIdArrayList.add(reservationBo.getPostID());
            if (updateTimes.contains(reservationBo.getUpdateTime())) {
                reserveStaffNoBoList.get(updateTimes.indexOf(reservationBo.getUpdateTime())).addPostId(reservationBo.getPostID());
            } else {
                if (!staffNos.contains(reservationBo.getStaffNo())) {
                    staffNos.add(reservationBo.getStaffNo());
                }
                updateTimes.add(reservationBo.getUpdateTime());
                ReserveStaffNoBo reserveStaffNoBo = new ReserveStaffNoBo(reservationBo.getUpdateTime(), reservationBo.getStaffNo());
                reserveStaffNoBo.addPostId(reservationBo.getPostID());
                reserveStaffNoBoList.add(reserveStaffNoBo);
            }
        }
        setPostIds();
    }

    /**
     * 设置分页
     */
    private void setPostIds() {
        StringBuilder ids = new StringBuilder();
        for (int i = pageIndex * 10; i < postIdArrayList.size() && i < (pageIndex + 1) * 10; i++) {
            ids.append(postIdArrayList.get(i)).append(",");
        }
        if (ids.length() > 0) {
            ids.deleteCharAt(ids.length() - 1);
            requestPostList(ids.toString());
        }
    }

    @Override
    protected void responsePostList(ArrayList<PostDo> temp) {
        int size = postIdArrayList.size();
        for (int i = 0; i < size; i++) {
            for (PostDo postDo : temp) {
                if (postIdArrayList.get(i).equalsIgnoreCase(postDo.getPostId())) {
                    postDoArrayList.add(postDo);
                }
            }
        }
        pageIndex++;
        if (pageIndex * 10 < postIdArrayList.size()) {
            setPostIds();
        } else {
            for (PostDo postDo : postDoArrayList) {
                for (ReserveStaffNoBo reserveStaffNoBo : reserveStaffNoBoList) {
                    if (reserveStaffNoBo.getPostIds().contains(postDo.getPostId())) {
                        reserveStaffNoBo.addPost(postDo);
                    }
                }
            }
            swipeRefreshLayout.setRefreshing(false);
            expMgr.notifyGroupItemRangeInserted(0, reserveStaffNoBoList.size());
            expMgr.expandAll();
            for (String staffNo : staffNos) {
                staffApi.setStaffNo(staffNo);
                staffApi.startRequest();
            }
            refreshUi();
        }
    }

    @Override
    protected void responseError() {
        super.responseError();
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void noData() {
        swipeRefreshLayout.setRefreshing(false);
        refreshUi();
    }

    private void refreshUi() {
        int size = reserveStaffNoBoList.size();
        rl_list.setVisibility(size == 0 ? View.GONE : View.VISIBLE);
        ll_no_list.setVisibility(size > 0 ? View.GONE : View.VISIBLE);
    }

    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(FragmentEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        reservationAdapter.setImEnable(bizUnitDo.isShowTalk());
                    }
                });
    }
}
